package com.godofgamblers.hotelmanagementsystem.handler;

import com.godofgamblers.hotelmanagementsystem.dto.Room_typeDTO;
import com.godofgamblers.hotelmanagementsystem.pojo.Cart;
import com.godofgamblers.hotelmanagementsystem.pojo.Room_Type;
import com.godofgamblers.hotelmanagementsystem.pojo.User;
import com.godofgamblers.hotelmanagementsystem.pojo.User_Level;
import com.godofgamblers.hotelmanagementsystem.service.CartService;
import com.godofgamblers.hotelmanagementsystem.service.RoomTypeService;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wzx
 * @date 2019/10/14 - 10:15
 * 购物车类的handler
 */
@Controller
@RequestMapping("/cart")
@Data
public class Selected_cartHandler {
    @Resource
    private CartService cartService;
    @Resource
    private RoomTypeService roomTypeService;
    private ModelAndView modelAndView = new ModelAndView();


    //用户点击购物车，查看购物车中东西（根据用户id,数据库查询遍历）
    @RequestMapping("/showcar")
    public ModelAndView showCart() throws ParseException {
        Session session = SecurityUtils.getSubject().getSession();    //取出session
        Object obj = session.getAttribute("user");   //获得user
        User user = (User) obj;  //当前用户
        /*User user = new User();
        user.setUser_id(1);*/
        //user.setUser_credit(12000);
        List<Cart> carts = cartService.findMyCart(user);    //通过user找到该用户的购物车集合。当前用户的购物车集合
        List<Room_typeDTO> roomTypeDTOS = new ArrayList<>();
        for (Cart cart : carts) {
            //将每条信息的入住时间和退房时间筛选出来，计算出入住时长
            String leave_time = cart.getPlan_leave_time();
            String stay_time = cart.getPlan_stay_time();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date leave = format.parse(leave_time);
            Date stay = format.parse(stay_time);

            int time = (int) (leave.getTime() - stay.getTime())/(60*60*24*1000);
           /* String leave = leave_time.replace("-","");
            String stay = stay_time.replace("-","");
            Integer time = Integer.parseInt(leave)-Integer.parseInt(stay);*/
            cart.setTime(time); //设置计算出来的居住时间

            //循环遍历该集合，将对应的roomg_type_id变为具体的房间信息 封装到dto中
            int room_type_id = cart.getRoom_type_id();
            Room_Type room_type = roomTypeService.findRoomType(room_type_id);
            //计算出总价格添加到对象中
            BigDecimal priceOnnight = room_type.getRoom_type_price();
            BigDecimal b = new BigDecimal(time);    //入住天数
            BigDecimal allPrice = priceOnnight.multiply(b);
            BigDecimal roomDiscountPrice = allPrice.multiply(room_type.getRoom_type_discount());


            BigDecimal roomprice =  roomDiscountPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal allprice =  allPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            cart.setAllprice(allprice);
            cart.setRoomDiscountPrice(roomprice);


            Room_typeDTO roomTypeDTO = new Room_typeDTO();  //创建一个对象
            roomTypeDTO.setRoom_type(room_type);    //将房间信息封装进去
            roomTypeDTO.setCart(cart);              //将购物车信息封装进去
            roomTypeDTOS.add(roomTypeDTO);          //将每个对象添加到集合中并返回
        }
       User user1 = (User) SecurityUtils.getSubject().getSession().getAttribute("user");

        //通过用户信息查到该用户的会员级别以及享有的折扣
        User_Level userLevel = cartService.findUserLevel(user);
        modelAndView.setViewName("front_cart.html");
        modelAndView.addObject("roomTypeDTO",roomTypeDTOS);
        modelAndView.addObject("userLevel",userLevel);
        modelAndView.addObject("user",user1);
        return modelAndView;
    }
    //用户选择房间类型点击加入购物车(参数:选择的房间类型，计划入住时间，计划退房时间的cart对象,)
    @RequestMapping("/add")
    @ResponseBody
    public String addCart(Cart cart, HttpServletResponse response) throws IOException {
        Session session = SecurityUtils.getSubject().getSession();    //取出session
        Object obj = session.getAttribute("user");   //获得user
        if (obj == null) {
            //未登录，重定向跳转登录界面，让其登录
            response.sendRedirect("/login");
            return "请先登录";
        }
        //已经登陆的情况下
        String stay_time = cart.getPlan_stay_time();
        String leave_time = cart.getPlan_leave_time();
        String[] ss  = stay_time.split("/");
        String[] sa  = leave_time.split("/");
        String plan_stay_time = ss[2]+"-"+ss[0]+"-"+ss[1];
        String plan_leave_time = sa[2]+"-"+sa[0]+"-"+sa[1];

        User user = (User) obj;
        //cart.setUser_id(1);
        cart.setUser_id(user.getUser_id());
        cart.setPlan_stay_time(plan_stay_time);
        cart.setPlan_leave_time(plan_leave_time);
        cartService.addCart(cart);  //添加该信息到数据库中
        return "添加成功";
    }
    //用户点击移除购物车中的某一项(参数：点击删除行的cart_id)
    @RequestMapping("/remove")
    @ResponseBody
    public String removeCart(String[] removeid){
        System.out.println("删除咯");
        for (String c: removeid) {
            Integer cart_id = Integer.parseInt(c);    //转化int类型
            cartService.deleteCart(cart_id);
        }
        return "删除成功";
    }



}
